/**********************************************************
 * FileUtil.java
 * Created by ankur
 * Last modified Date: Sep 9, 2008 2:42:22 PM by ankur
 * Version : 0.1
 * Copyright (c) 2008 - 2008 cyberThink Infotech Pvt. Ltd., All rights reserved.
 **********************************************************/

package com.printeverywhere.util;

import org.apache.log4j.Logger;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * The Class FileUtil.
 */
public class FileUtil {

	/** Logger for this class. */
	private static final Logger logger = Logger.getLogger(FileUtil.class);

	/**
	 * Show dir.
	 *
	 * @param dir the dir
	 * @param list the list
	 *
	 * @return the list< string>
	 *
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	public static List<String> showDir(String dir, List<String> list)
			throws IOException {
		if (logger.isDebugEnabled()) {
			logger.debug("showDir(String, List<String>) - start"); //$NON-NLS-1$
		}

		File file = new File(dir);
		if (file.isDirectory()) {
			list.add(file.getAbsolutePath());
		}
		if (file.isDirectory()) {
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++)
				showDir(files[i].getAbsolutePath(), list);
		}

		if (logger.isDebugEnabled()) {
			logger.debug("showDir(String, List<String>) - end"); //$NON-NLS-1$
		}
		return list;
	}

	/**
	 * Show file and dir.
	 *
	 * @param path the path
	 * @param list the list
	 *
	 * @return the list< system dir>
	 *
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	public static List<SystemDir> showFileAndDir(String path,
			List<SystemDir> list) throws IOException {
		if (logger.isDebugEnabled()) {
			logger.debug("showFileAndDir(String, List<SystemDir>) - start"); //$NON-NLS-1$
		}

		File file = new File(path);
		SystemDir systemDir = new SystemDir();
		if (file.isDirectory()) {
			systemDir.setDir("Yes");
		} else {
			systemDir.setDir("No");
		}

		if (file.canExecute()) {
			systemDir.setExecute("Yes");
		} else {
			systemDir.setExecute("No");
		}

		if (file.canRead()) {
			systemDir.setRead("Yes");
		} else {
			systemDir.setRead("No");
		}
		if (file.canWrite()) {
			systemDir.setWrite("Yes");
		} else {
			systemDir.setWrite("No");
		}
		systemDir.setFileName(file.getAbsolutePath());
		list.add(systemDir);
		if (file.isDirectory()) {
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++)
				list = showFileAndDir(files[i].getAbsolutePath(), list);
		}

		if (logger.isDebugEnabled()) {
			logger.debug("showFileAndDir(String, List<SystemDir>) - end"); //$NON-NLS-1$
		}
		return list;
	}

	 /**
 	 * The main method.
 	 *
 	 * @param a the arguments
 	 *
 	 * @throws Exception the exception
 	 */


		  /**
  		 * Zip folder.
  		 *
  		 * @param srcFolder the src folder
  		 * @param destZipFile the dest zip file
  		 *
  		 * @throws Exception the exception
  		 */
  		static public void zipFolder(String srcFolder, String destZipFile) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("zipFolder(String, String) - start"); //$NON-NLS-1$
		}

		    ZipOutputStream zip = null;
		    FileOutputStream fileWriter = null;

		    fileWriter = new FileOutputStream(destZipFile);
		    zip = new ZipOutputStream(fileWriter);

		    addFolderToZip("", srcFolder, zip);
		    zip.flush();
		    zip.close();

			if (logger.isDebugEnabled()) {
			logger.debug("zipFolder(String, String) - end"); //$NON-NLS-1$
		}
		  }

		  /**
  		 * Adds the file to zip.
  		 *
  		 * @param path the path
  		 * @param srcFile the src file
  		 * @param zip the zip
  		 *
  		 * @throws Exception the exception
  		 */
  		static private void addFileToZip(String path, String srcFile, ZipOutputStream zip)
		      throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("addFileToZip(String, String, ZipOutputStream) - start"); //$NON-NLS-1$
		}

		    File folder = new File(srcFile);
		    if (folder.isDirectory()) {
		      addFolderToZip(path, srcFile, zip);
		    } else {
		      byte[] buf = new byte[1024];
		      int len;
		      FileInputStream in = new FileInputStream(srcFile);
		      zip.putNextEntry(new ZipEntry(path + File.separator + folder.getName()));
		      while ((len = in.read(buf)) > 0) {
		        zip.write(buf, 0, len);
		      }
		    }

			if (logger.isDebugEnabled()) {
			logger.debug("addFileToZip(String, String, ZipOutputStream) - end"); //$NON-NLS-1$
		}
	  }

  		/**
  		 * Adds the folder to zip.
  		 *
  		 * @param path the path
  		 * @param srcFolder the src folder
  		 * @param zip the zip
  		 *
  		 * @throws Exception the exception
  		 */
  		static private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip)
		      throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("addFolderToZip(String, String, ZipOutputStream) - start"); //$NON-NLS-1$
		}

		    File folder = new File(srcFolder);
		    for (String fileName : folder.list()) {
		      if (path.equals("")) {
		        addFileToZip(folder.getName(), srcFolder + File.separator + fileName, zip);
		      } else {
		        addFileToZip(path + File.separator + folder.getName(), srcFolder + File.separator + fileName, zip);
		      }
		    }

			if (logger.isDebugEnabled()) {
			logger.debug("addFolderToZip(String, String, ZipOutputStream) - end"); //$NON-NLS-1$
			}
		  }

  			/**
  			 * Make g zip.
  			 *
  			 * @param fileName the file name
  			 *
  			 * @throws IOException Signals that an I/O exception has occurred.
  			 * @throws FileNotFoundException the file not found exception
  			 */
  			public static void makeGZip(String fileName)throws IOException, FileNotFoundException
		   {
		if (logger.isDebugEnabled()) {
			logger.debug("makeGZip(String) - start"); //$NON-NLS-1$
			}

		      File file = new File(fileName);
		      FileOutputStream fos = new FileOutputStream(file + ".gzip");
		      GZIPOutputStream gzos = new GZIPOutputStream(fos);
		      //Create a buffered input stream out of the file we are
		      //trying to add into the gzip archive.
		      FileInputStream fin = new FileInputStream(file);
		      BufferedInputStream in = new BufferedInputStream(fin);
		      //Create a buffer for reading raw bytes from the file.
		      byte[] buf = new byte[1024];
		      //The len variable will keep track of how much we
		      //are able to actually read each time we try.
		      int len;
		      //Read from the file and write to the gzip archive.
		      while ((len = in.read(buf)) >= 0) {
		         gzos.write(buf,0,len);
		      }
		      in.close();
		      gzos.close();

				if (logger.isDebugEnabled()) {
			logger.debug("makeGZip(String) - end"); //$NON-NLS-1$
				}
		   }

  			public static boolean deleteFile(File dirPath){

  				if( dirPath.exists() ) {
  			      File[] files = dirPath.listFiles();
  			      for(int i=0; i<files.length; i++) {
  			         if(files[i].isDirectory()) {
  			        	deleteFile(files[i]);
  			         }
  			         else {
  			           files[i].delete();
  			         }
  			      }
  			    }
  				 return( dirPath.delete() );
  			}

  			public static void editFile(String filePath, String addHomePageUrl) throws IOException{
  				try{
	  	 	          boolean append = true;
	  	 	          FileWriter fw = new FileWriter(filePath,append);
	  	 	          fw.write(addHomePageUrl+"\n");//appends the string to the file
	  	 	          fw.close();
	  	 	     }catch(IOException ioe){
	  	 	          System.err.println("IOException: " + ioe.getMessage());
	  	 	      }
  			}

  			public static void editFileByLocation(String filePath, String addHomePageUrl) throws IOException{
  				try {
  					File file = new File(filePath);
  					FileReader fr = new FileReader(file);

  					BufferedReader in = new BufferedReader(fr);
  					String h=in.readLine() ;
  					List<String> l = new ArrayList<String>();
  					l.add(h);
  					while(h != null){
	  					if(h.equalsIgnoreCase("# skip everything else")){
	  						break;
	  					}
	  					l.add(h);
	  					h=in.readLine();
  					}
  					file.delete();
  					PrintWriter writer=new PrintWriter(file);
  					for (Iterator iterator = l.iterator(); iterator.hasNext();) {
						String st = (String) iterator.next();
						writer.append("\n");
						writer.append(st);

					}
  					//Jo Add karna hai wo karo
  					writer.append("+^http://([a-z0-9]*\\.)*");
  					writer.append(addHomePageUrl);
  					writer.append("/");
  					writer.append("\n");
  					writer.append("\n");
  					writer.append("# skip everything else");
  					writer.append("\n");
  					writer.append("-.");
  					writer.append("\n");
  					writer.flush();
  					writer.close();
				} catch (Exception e) {
					logger.error(e.getMessage());
				}
  			}

  			public static String readFile(String filename) throws IOException {
  			   String lineSep = System.getProperty("line.separator");
  			   BufferedReader br = new BufferedReader(new FileReader(filename));
  			   String nextLine = "";
  			   StringBuffer sb = new StringBuffer();
  			   while ((nextLine = br.readLine()) != null) {
  			     sb.append(nextLine);
  			     //
  			     // note:
  			     //   BufferedReader strips the EOL character
  			     //   so we add a new one!
  			     //
  			     sb.append(lineSep);
  			   }
  			   return sb.toString();
  			}

  			public static List<String> getFileNameList(String folderName) throws IOException {
  				File folder = new File(folderName);
  				File[] listOfFiles = folder.listFiles();
  				List<String> fileNameList = new ArrayList<String>();
  				for (int i = 0; i < listOfFiles.length; i++) {
  			      if (listOfFiles[i].isFile()) {
  			    	fileNameList.add(listOfFiles[i].getName());
  			      }
  				}
  				return fileNameList;
   			}

  			public static void copyDirectory(File sourceDir, File destDir) throws IOException {
				if (!destDir.exists()) {
					destDir.mkdir();
				}

				File[] children = sourceDir.listFiles();

				for (File sourceChild : children) {
					String name = sourceChild.getName();
					File destChild = new File(destDir, name);
					if (sourceChild.isDirectory()) {
//						copyDirectory(sourceChild, destChild);
					}
					else {
						copyFile(sourceChild, destChild);
					}
				}
			}

  			public static void copyFile(File source, File dest) throws IOException {
				if (!dest.exists()) {
					dest.createNewFile();
				}

				InputStream in = null;
				OutputStream out = null;
				try {
					in = new FileInputStream(source);
					out = new FileOutputStream(dest);
					byte[] buf = new byte[1024];
					int len;
					while ((len = in.read(buf)) > 0) {
						out.write(buf, 0, len);
					}
				}finally {
					in.close();
					out.close();
				}
			}

  			public static void writeFile(String friveraOutfile, String data){//String name of file, String array to be written
  				File fileNameout = new File(friveraOutfile);
  				try {
  				 BufferedWriter writer = new BufferedWriter(new FileWriter (fileNameout));
  				 writer.write(data); //need delimiters between data in file;also, reader reads a line
  				 writer.close();
  				 }

  				catch(FileNotFoundException e) {
  				 System.out.println("File not found");
  				}

  				catch(IOException e) {
  				 System.out.println("Error with reading file:" );
  				}
  			}

  			public static String getFileExtension(String fileName){
  				String extension = null;
  				try {
  					int mid= fileName.lastIndexOf(".");
  				    String fname=fileName.substring(0,mid);
  				    extension=fileName.substring(mid+1,fileName.length());
  				    logger.info("File name = "+fname);
  				    logger.info("Extension = "+extension);
				} catch (Exception e) {
					logger.error("Error in getting file extension." + e.getCause());
				}
  				return extension;
  			}
  			public static void main(String[] a) throws Exception {
  				/*
				 * if (logger.isDebugEnabled()) { logger.debug("main(String[]) -
				 * start"); //$NON-NLS-1$ }
				 *
				 * zipFolder("D:\\My Projects\\My Project Info\\Virticle
				 * Auction\\For Documents only", "c:\\a.zip"); zipFolder("D:\\My
				 * Projects\\My Project Info\\Virticle Auction\\Doc",
				 * "c:\\a.zip");
				 *
				 * if (logger.isDebugEnabled()) { logger.debug("main(String[]) -
				 * end"); //$NON-NLS-1$ }
				 */

//  				deleteFile(new File("C:/nutch-0.9/crawl"));

  				//editFile("C:/nutch-0.9/urls/url.txt","http://www.sun123.com/");
  		 				editFileByLocation("C:\\nutch-0.9\\conf\\crawl-urlfilter.txt","javaranch.com");

  				  }
}